package com.seari.monitor.impl;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.seari.monitor.MiddlewareMonitor;

public class RabbitMqMiddlewareMonitor extends MiddlewareMonitor{
	
	final static Logger logger = LoggerFactory.getLogger(RabbitMqMiddlewareMonitor.class);
	private static String url = "http://127.0.0.1:15672/api/aliveness-test/%2F";
	private static String username = "guest";
	private static String password = "guest";
	private static String host = "127.0.0.1";
	private static Integer port = 5672;
	private static String vhost = "/";
	private final static String name = "rabbitMq";
	
	

	@Override
	public boolean isClient() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void monitorData() {
		while(true) {
			 logger.info("检测 rabbitmq 服务 ...");
			 if(!this.checkAMQPPing()) {
				 logger.info("重启 rabbitMq 服务...");
				 super.restartService(name,40);
				 continue;
			 }
			 
			 logger.info("验证 rabbitmq 服务健康性 ...");
			 if(!this.checkAMQPAlive()) {
				 logger.info("重启 rabbitMq 服务...");
				 super.restartService(name,30);
			 }
			 
			 try {
				TimeUnit.MINUTES.sleep(2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	
	
	/**
	 * 创建测试连接监测
	 * @return
	 */
	public boolean checkAMQPPing(){
		boolean res = true;
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setPort(port);
        connectionFactory.setVirtualHost(vhost);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        Connection connection = null;
        Channel channel = null;
        try {
        	connection = connectionFactory.newConnection();
        	channel = connection.createChannel();
        } catch (IOException | TimeoutException e ) {
            res = false;
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return res;
    }
	
	
	public boolean checkAMQPAlive() {
		BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
		credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST,AuthScope.ANY_PORT),new UsernamePasswordCredentials(username,password));
		CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
		HttpGet httpGet = new HttpGet(url); 
		CloseableHttpResponse response = null;
		boolean res = true;
		try {
			response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();
			if(entity != null) {
					String data = EntityUtils.toString(entity,"utf-8");
					if(!data.equals("{\"status\":\"ok\"}")) {
						res = false;
					}
			}
		} catch (ClientProtocolException e) {
			res = false;
		} catch (IOException e) {
			res = false;
		} finally {
			try {
				if(response != null) {
					response.close();
				}
				if(client != null) {
					client.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return res;
	}
	
	public static void main(String[] args) {
		RabbitMqMiddlewareMonitor mq = new RabbitMqMiddlewareMonitor();
		mq.monitorData();
	}

}
